package com.example.im.service.impl;

import com.example.im.model.Message;
import com.example.im.service.MessageService;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public void saveMessage(Message message) {
        String sql = "INSERT INTO chat_message (from_user, to_user, group_id, content, timestamp) VALUES (?, ?, ?, ?, ?)";
        jdbcTemplate.update(sql,
                message.getFromUser(),
                null,
                message.getGroupId(),
                message.getContent(),
                message.getTimestamp()
        );
    }
    @Override
    public List<Message> getMessagesByGroup(String groupId) {
        String sql = "SELECT * FROM chat_message WHERE group_id = ? ORDER BY timestamp ASC";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Message.class), groupId);
    }

    @Override
    public List<Message> getMessagesByUser(String fromUser) {
        String sql = "SELECT * FROM chat_message WHERE from_user = ? ORDER BY timestamp DESC";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Message.class), fromUser);
    }
}